<template>
	<view class="container">
		<!-- 表单内容 -->
		<view class="form-content">
			<!-- 第一部分 -->
			<view class="form-section">
				<u-form :model="form" ref="uForm" labelWidth="70px">
					<u-form-item label="联系电话:" prop="phone">
						<u-input v-model="form.phone" placeholder="请输入联系电话" />
					</u-form-item>
					<u-form-item label="所在区域:" prop="area">
						<!-- <u-input v-model="form.area" placeholder="请选择所在区域" type="select" @click="onChooseMap" /> -->
						<u-button type="primary" text="请选择所在区域" :plain="true" @click="onChooseMap" />
					</u-form-item>
					<u-form-item label="小区街道:" prop="street">
						<u-input v-model="form.street" placeholder="请输入小区或街道名" />
					</u-form-item>
				</u-form>
			</view>

			<view class="form-section">
				<u-form :model="form" ref="uForm" labelWidth="70px">
					<u-form-item label="家教方式:" prop="teachingMethod">
						<u-picker :show="showTeachingMethodPicker" ref="teachingMethodPicker"
							:columns="teachingMethodColumns" @confirm="confirmTeachingMethod"
							@cancel="cancelTeachingMethod"></u-picker>
						<u-button @click="showTeachingMethodPicker = true" class="margin-btn select-btn">
							<text class="btn-text">{{ form.teachingMethod || "选择家教方式" }}</text>
							<text class="jtou iconfont-v2 icon-f11-copy"></text>
						</u-button>
					</u-form-item>

					<u-form-item label="家教科目:" prop="subject">
						<u-picker :show="showSubjectPicker" ref="subjectPicker" :columns="subjectColumns"
							@confirm="confirmSubject" @change="onSubjectChange" @cancel="cancelSubject"></u-picker>
						<u-button @click="showSubjectPicker = true" class="margin-btn select-btn">
							<text class="btn-text">{{ form.subject || "选择家教科目" }}</text>
							<text class="jtou iconfont-v2 icon-f11-copy"></text>
						</u-button>
					</u-form-item>

					<u-form-item label="家教薪酬:" prop="salary">
						<u-picker :show="showSalaryPicker" ref="salaryPicker" :columns="salaryColumns"
							@confirm="confirmSalary" @cancel="cancelSalary"></u-picker>
						<u-button @click="showSalaryPicker = true" class="margin-btn select-btn">
							<text class="btn-text">{{ form.salary || "选择意向家教薪酬" }}</text>
							<text class="jtou iconfont-v2 icon-f11-copy"></text>
						</u-button>
					</u-form-item>
				</u-form>
				<view class="salary-reference" @click="viewSalaryReference">查看教员薪酬参考</view>
			</view>

			<!-- 第三部分 -->
			<view class="form-section">
				<u-form :model="form" ref="uForm" labelWidth="70px">
					<u-form-item label="学员概况:" prop="studentProfile">
						<u-input v-model="form.studentProfile" placeholder="如性别,年级,科目,成绩等.." type="textarea" />
					</u-form-item>
					<u-form-item label="教员要求:" prop="teacherRequirements">
						<u-input v-model="form.teacherRequirements" placeholder="如性别,性格,资历,经验等.." type="textarea" />
					</u-form-item>
					<u-form-item label="课时安排:" prop="classSchedule">
						<u-input v-model="form.classSchedule" placeholder="如周一到周五晚上7-9点.." type="textarea" />
					</u-form-item>
				</u-form>
			</view>
		</view>

		<!-- 底部固定按钮 -->
		<view class="bottom-actions">
			<view class="action-buttons">
				<u-button type="primary" :plain="true" text="联系客服" icon="chat" @click="contactService"></u-button>
				<u-button type="primary" text="免费发布家教需求" @click="submitOrder"></u-button>
			</view>
		</view>

		<u-picker v-model="showAreaPicker" mode="region" @confirm="confirmArea"></u-picker>
	</view>
</template>

<script>
	import {
		submitStudentOrder
	} from "@/utils/mockApi.js";
	import * as api from '@/api/family'
	
	export default {
		data() {
			return {
				location_lock:false,
				// 表单数据
				form: {
					phone: "",
					area: "",
					street: "",
					teachingMethod: "",
					subject: "",
					salary: "",
					studentProfile: "",
					teacherRequirements: "",
					classSchedule: "",
					regionProvince:"",
					regionCity:"",
					regionDistrict:""
				},

				// 选择器显示状态
				showAreaPicker: false,
				showTeachingMethodPicker: false,
				showSubjectPicker: false,
				showSalaryPicker: false,

				// 家教方式选择器数据
				teachingMethodColumns: [
					["线上", "线下"]
				],

				// 科目选择器数据（二级联动）
				subjectColumns: [
					[],
					[], // 默认值
				],
				subjectColumnData: [
					// ["小学语文", "小学数学", "小学英语"],
					// ["初中语文", "初中数学", "初中英语", "初中物理"],
				],

				// 薪酬选择器数据
				salaryColumns: [
					["60元/小时", "70元/小时", "80元/小时", "100元/小时", "面议"]
				],
			};
		},
		onShow() {
			this.getSubject()
		},
		methods: {
			getSubject(){
				api.getCatAndCourseApi().then(res=>{
					let list = res.data
					if(list.length>0){
						for (var index = 0; index < list.length; index++) {
							this.subjectColumns[0].push(list[index]['name']);
							let courseList = list[index]['list']
							if(courseList.length>0){
								let temp = [];
								for (var i = 0; i < courseList.length; i++) {
									temp.push(courseList[i]['name'])
								}
								this.subjectColumnData.push(temp)
							}else{
								this.subjectColumnData[index] = []
							}
						}
						this.subjectColumns[1] = this.subjectColumnData[0] || [];
					}
				})
			},
			/**
			 * 选择地区
			 */
			onChooseMap() {
				let that = this
				// 使用uni.chooseLocation选择位置
				uni.chooseLocation({
					success: (res) => {
						console.log(res)
						// 获取位置信息
						const locationName = res.name || '';
						const address = res.address || '';

						// 组合完整地址显示在区域字段
						if (locationName) {
							this.form.area = locationName;
						} else if (address) {
							this.form.area = address;
						} else {
							this.form.area = `${res.latitude},${res.longitude}`;
						}

						// 如果有详细地址，也填充到街道字段
						if (address && !this.form.street) {
							this.form.street = address;
						}
						let form = {
							longitude:res.longitude,
							latitude: res.latitude
						}
						if(!that.location_lock){
							api.addressAnalysis(form).then( data =>{
								
								that.form.regionCity = data.data.address_component.city;
								that.form.regionDistrict =  data.data.address_component.district;
								that.form.regionProvince = data.data.address_component.province;  
								
							
								
								that.location_timer  = setTimeout(()=>{
									that.location_lock = true;
								},1000 * 60);
							});
						}
						
						uni.showToast({
							title: '位置选择成功',
							icon: 'success',
							duration: 1500
						});
					},
					fail: (err) => {
						console.error('选择位置失败:', err);

						// 如果选择位置失败，降级使用区域选择器
						this.showAreaPicker = true;
					}
				});
			},

			confirmArea(e) {
				this.form.area = e.result.join(" ");
				this.showAreaPicker = false;
			},

			// 家教方式选择相关方法
			confirmTeachingMethod(e) {
				console.log(e)
				this.form.teachingMethod = e.value[0];
				this.showTeachingMethodPicker = false;
			},

			cancelTeachingMethod() {
				this.showTeachingMethodPicker = false;
			},

			// 科目选择相关方法（二级联动）
			onSubjectChange(e) {
				const {
					columnIndex,
					index,
					picker = this.$refs.subjectPicker
				} = e;
				
				// 当第一列值发生变化时，更新第二列对应的选项
				if (columnIndex === 0) {
					picker.setColumnValues(1, this.subjectColumnData[index]);
				}
			},

			confirmSubject(e) {
				this.form.subject = e.value[0]+'-'+e.value[1];
				this.form.subjectCategory =  e.value[0]
				this.form.subjectCourse =  e.value[1]
				this.showSubjectPicker = false;
			},

			cancelSubject() {
				this.showSubjectPicker = false;
			},

			// 薪酬选择相关方法
			confirmSalary(e) {
				this.form.salary = e.value[0];
				this.showSalaryPicker = false;
			},

			cancelSalary() {
				this.showSalaryPicker = false;
			},

			// 页面导航相关方法
			goBack() {
				uni.navigateBack();
			},

			viewSalaryReference() {
				uni.navigateTo({
					url: "/pages/jiajiao/salary-reference",
				});
			},

			// 联系客服
			contactService() {
				uni.showModal({
					title: "联系客服",
					content: "是否联系在线客服？",
					success: (res) => {
						if (res.confirm) {
							uni.showToast({
								title: "正在为您转接客服",
								icon: "none",
							});
						}
					},
				});
			},

			/**
			 * 提交订单
			 */
			async submitOrder() {
				// 表单验证
				if (!this.validateForm()) {
					return;
				}

				// 确认发布
				uni.showModal({
					title: "确认发布",
					content: "是否确认发布家教需求？",
					success: async (res) => {
						if (res.confirm) {
							// 显示加载提示
							uni.showLoading({
								title: "发布中...",
								mask: true,
							});

							try {
								if(this.form.teachingMethod == "线上"){
									this.form.teachingMethod = 2
								}else{
									this.form.teachingMethod = 1
								}
								// 准备提交的数据
								const submitData = {
									...this.form
								};
								
								// 调用mock API提交数据
								const response = await api.publishOrderApi(submitData);

								uni.hideLoading();

								if (response.code === 200) {
									// 提交成功
									uni.showToast({
										title: "发布成功",
										icon: "success",
										duration: 1000,
									});

									// 延迟返回上一页
									// setTimeout(() => {
									// 	uni.navigateBack();
									// }, 1000);
								} else {
									// 提交失败
									uni.showModal({
										title: "发布失败",
										content: response.message || "发布失败，请重试",
										showCancel: false,
									});
								}
							} catch (error) {
								uni.hideLoading();
								console.error("提交订单失败:", error);
								uni.showModal({
									title: "发布失败",
									content: "网络错误，请检查网络后重试",
									showCancel: false,
								});
							}
						}
					},
				});
			},

			/**
			 * 表单验证
			 * @returns {boolean}
			 */
			validateForm() {
				if (!this.form.phone.trim()) {
					uni.showToast({
						title: "请输入联系电话",
						icon: "none",
					});
					return false;
				}

				// 手机号格式验证
				const phoneReg = /^1[3-9]\d{9}$/;
				if (!phoneReg.test(this.form.phone)) {
					uni.showToast({
						title: "请输入正确的手机号",
						icon: "none",
					});
					return false;
				}

				if (!this.form.area.trim()) {
					uni.showToast({
						title: "请选择所在区域",
						icon: "none",
					});
					return false;
				}

				if (!this.form.street.trim()) {
					uni.showToast({
						title: "请输入小区或街道名",
						icon: "none",
					});
					return false;
				}

				if (!this.form.teachingMethod) {
					uni.showToast({
						title: "请选择家教方式",
						icon: "none",
					});
					return false;
				}

				if (!this.form.subject) {
					uni.showToast({
						title: "请选择家教科目",
						icon: "none",
					});
					return false;
				}

				if (!this.form.salary) {
					uni.showToast({
						title: "请选择家教薪酬",
						icon: "none",
					});
					return false;
				}

				if (!this.form.studentProfile.trim()) {
					uni.showToast({
						title: "请填写学员概况",
						icon: "none",
					});
					return false;
				}

				if (!this.form.teacherRequirements.trim()) {
					uni.showToast({
						title: "请填写教员要求",
						icon: "none",
					});
					return false;
				}

				if (!this.form.classSchedule.trim()) {
					uni.showToast({
						title: "请填写课时安排",
						icon: "none",
					});
					return false;
				}

				return true;
			}
		}
	};
</script>

<style lang="scss" scoped>
	@import "@/uni.scss";

	.container {
		padding: 24rpx;
		padding-bottom: 150rpx;
		/* 为底部固定按钮留出空间 */
	}

	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: #00c8c8;
		padding: 10px 20px;
		color: #fff;
	}

	.header-title {
		font-size: 18px;
		font-weight: bold;
	}

	.form-content {
		margin-top: 2rpx;
	}

	.form-section {
		border: 1px solid #e5e5e5;
		border-radius: 8rpx;
		padding: 30rpx;
		background-color: #ffffff;
		margin-bottom: 20rpx;
	}

	/* 底部固定按钮 */
	.bottom-actions {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: white;
		padding: 20rpx;
		border-top: 2rpx solid #f0f0f0;
		z-index: 100;
		margin-top: 20rpx;
	}

	.action-buttons {
		display: flex;
		gap: 20rpx;
	}

	.salary-reference {
		text-align: right;
		color: #ED6567;
		margin-top: 18rpx;
		margin-right: 10rpx;
		font-size: 20rpx;
	}

	::v-deep .form-section .u-form-item__body__left__content__label,
	::v-deep .form-section .u-form-item__body__left__content {
		font-size: 24rpx !important;
		/* font-weight: bold !important; */
	}

	::v-deep .u-form-item__body__right {
		margin-left: 10rpx !important;
	}

	::v-deep .form-section .u-form-item__body__right {
		flex: 1;
		padding-left: 10rpx;
	}

	/* 让按钮文字靠左，看起来像表单项 */
	::v-deep .u-button--default.u-button--plain {
		text-align: left;
	}

	.margin-btn {
		margin: 5rpx;
	}

	/* 选择按钮样式 */
	.select-btn {
		display: flex;
		justify-content: space-between;
		align-items: center;
		text-align: left;
	}

	.btn-text {
		flex: 1;
		text-align: left;
	}

	/* 统一输入框字体大小 */
	::v-deep .uni-input-input {
		font-size: 24rpx;
	}

	/* 统一placeholder字体大小 */
	::v-deep .uni-input-placeholder {
		font-size: 24rpx;
	}

	/* uview输入框placeholder样式 */
	::v-deep .u-input__content__field-wrapper__field::placeholder {
		font-size: 24rpx;
	}

	.jtou {
		color: #999;
		font-size: 36rpx;
	}
</style>